<?php
declare (strict_types = 1);
/**
 * 管理员
 */
namespace app\common\model;

class Admin extends BaseModel
{
    public function adminRoleHasOne()
    {
        return $this->hasOne(AdminRole::class, 'id', 'roleId');
    }

    /**
     * 部门表关联实例
     */
    public function adminDeptHasMany()
    {
        return $this->hasMany(AdminDept::class, 'id');
    }

    /**
     * 频道表关联实例
     */
    public function adminChannelHasMany()
    {
        return $this->hasMany(ChannelInfo::class, 'id');
    }
    
    /**
     * 管理员列表
     */
    public function adminList($whereAdmin = [], $whereRole = [], $offset = 1, $length = 20, $ordername, $order="desc")
    {
        $field = ['id', 'username', 'truename', 'head_img', 'login_ip', 'enable', 'roleId', 'depart', 'channel', 'create_time', 'up_time', 'mobile', 'email'];

        $fieldRole = ['id', 'name'];

        $list = self::with([
            'adminRoleHasOne' => function ($query) use ($whereRole, $fieldRole) {
                $query->withField($fieldRole)->hidden(['id'])->where($whereRole);
            }
        ])->field($field)->where($whereAdmin)->limit(($offset-1) * $length, $length)->order([$ordername => $order])->select();

        foreach($list as &$item) {
            if(!empty($item->depart)){
                $item->deptList = self::adminDeptHasMany()->field('id, name')->where('id', 'in', $item->depart)->select()->toArray();
            }
            if(!empty($item->channel)){
                $item->channelList = self::adminChannelHasMany()->field('id, channel_name as name')->where('id', 'in', $item->channel)->select()->toArray();
            }            
        }

        $count = self::where($whereAdmin)->count('id');
        return [
            'users'  => $list,
            'total' => $count,
            'pagenum' => $offset
        ];
    }

    /**
     * 管理员详情信息
     */
    public function adminInfo($where) 
    {
        $res = self::info($where);    
        
        if(!empty($res->roleId)) {
            $res->rolsInfo = self::adminRoleHasOne()->field('id, name')->where('id', '=', $res->roleId)->select()->toArray();
        }
        
        if(!empty($res->depart)) {
            $res->deptList = self::adminDeptHasMany()->field('id, name')->where('id', 'in', $res->depart)->select()->toArray();
        }

        if(!empty($res->channel)) {
            $res->channelList = self::adminChannelHasMany()->field('id, channel_name as name')->where('id', 'in', $res->channel)->select()->toArray();
        }
        // var_dump($res);
        return $res;
    }
}